package common

import (
	"net/http"
	"sync"
	"time"

	"kingbloc.sso/user"

	"kingbloc.util/util"
)

var lockSignin sync.Mutex

// 注册用户
func Signin(w http.ResponseWriter, r *http.Request) {
	lockSignin.Lock()
	defer lockSignin.Unlock()
	uname := r.FormValue("uname")
	password := r.FormValue("pwd")
	////validate
	var isMobOk bool = false
	var isEmailOk bool = false
	var pwdIsOk bool = false
	var clientTmpUser = &user.User{}
	user := user.User{}

	if uname != "" {
		isMobOk = util.RegexpMobile.MatchString(uname)
		if isMobOk {
			clientTmpUser.Mobile = uname
			user.Mobile = uname
		}

		isEmailOk = util.RegexpEmail.MatchString(uname)
		if isEmailOk {
			clientTmpUser.Email = uname
			user.Email = uname
		}

		if isMobOk || isEmailOk {
			clientTmpUser.Alias = uname
			user.Alias = uname
		} else {
			util.WriteJSON(w, "uname is error.")
			return
		}

	}
	if password != "" {
		pwdIsOk = util.RegexpPassword.MatchString(password)
		if !pwdIsOk {
			util.WriteJSON(w, "password is error.")
			return
		}

	} else {
		util.WriteJSON(w, 0)
		return
	}

	//
	clientTmpUser = clientTmpUser.ByMobile()
	if clientTmpUser != nil || password == "" {
		util.WriteJSON(w, clientTmpUser)
		return
	}

	password = util.Md5EncodeForPassword(password)
	user.Password = password
	user.Create = time.Now()
	user.Last = user.Create
	userOk, _, _ := user.Add()

	util.WriteJSON(w, userOk)

}
